package com.tangkun.environment.adapter;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;

import com.tangkun.environment.R;
import com.tangkun.environment.activity.CaptureImageActivity;
import com.tangkun.environment.activity.DeleteImageActivity;

/**
 * @author tangkun
 * @ClassName: ImageFileAdapter
 * @Description: TODO(相册适配器(包含添加图片))
 * @date 2016年4月26日 下午1:37:03
 */
public class ImageFileAdapter extends BaseAdapter {

    public static final int REQUEST_CODE_CAPTURE_IMAGE = 1;// 查看大图可能会有选中或删除和拍照
    private Activity activity;
    private LayoutInflater layoutInflater;
    private int res;
    private static final int IMAGE_W = 400;
    private static final int IMAGE_H = 400;
    // 最大图片上传张数
    private static final int IMAGE_NUM = 9;
    // 现在是微博和成长记录不用选择原图
    private boolean isShowOriginal = true;

    public ImageFileAdapter(Activity activity, int res) {
        this.activity = activity;
        this.layoutInflater = LayoutInflater.from(activity);
        this.res = res;
    }

    private List<File> fileList = new ArrayList<File>();

    public List<File> getFileList() {
        if (fileList == null) {
            fileList = new ArrayList<File>();
        }
        return fileList;
    }

    public void setFileList(List<File> fileList) {
        this.fileList.clear();
        this.fileList.addAll(fileList);
    }

    public boolean isShowOriginal() {
        return isShowOriginal;
    }

    public void setShowOriginal(boolean isShowOriginal) {
        this.isShowOriginal = isShowOriginal;
    }

    @Override
    public int getCount() {
        return Math.min(9, (fileList == null ? 0 : fileList.size()) + 1);
    }

    @Override
    public Object getItem(int arg0) {
        // return null;
        return fileList.get(arg0);
    }

    @Override
    public long getItemId(int arg0) {
        return arg0;
    }

    class ViewHolder {
        public ImageView imageView;
        public ImageView cameraImageView;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup viewGroup) {
        ViewHolder holder;
        if (convertView == null) {
            convertView = layoutInflater.inflate(res, null);
            holder = new ViewHolder();
            holder.imageView = (ImageView) convertView.findViewById(R.id.image);
            holder.cameraImageView = (ImageView) convertView.findViewById(R.id.camera_image);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        if (position == fileList.size()) {// 添加按钮
            holder.cameraImageView.setVisibility(View.VISIBLE);
            holder.imageView.setVisibility(View.INVISIBLE);
            holder.imageView.setImageResource(R.mipmap.ic_star_add);
            holder.cameraImageView.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // 添加按钮，去相册
                    Intent intent = new Intent(activity, CaptureImageActivity.class);
                    intent.putExtra("w", IMAGE_W);
                    intent.putExtra("h", IMAGE_H);
                    intent.putExtra("custom", false);
                    intent.putExtra("module", "weibo");
                    intent.putExtra("num", IMAGE_NUM - getFileList().size());
                    intent.putExtra("isShowOriginal", isShowOriginal());
                    activity.startActivityForResult(intent, REQUEST_CODE_CAPTURE_IMAGE);
                }
            });
        } else {// 图片item
            holder.cameraImageView.setVisibility(View.GONE);
            holder.imageView.setVisibility(View.VISIBLE);
            // 由于现在可以传原图回来，所以这里要显示缩略图，否则会内存溢出的，因此不能采用ImageLoader那种图片展示方式了
            holder.imageView.setImageBitmap(getImageThumbnail(getItem(position).toString(), 200, 200));
//			ImageLoader.getInstance().displayImage(Uri.fromFile(fileList.get(position)).toString(), holder.imageView, displayImageOptions);

            holder.imageView.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // 预览图片，可以删除
                    List<String> urlList = new ArrayList<String>();
                    if (fileList != null) {
                        for (int i = 0; i < fileList.size(); i++) {
//                            urlList.add(Uri.fromFile(fileList.get(i)).toString());
                            urlList.add(fileList.get(i).getPath());
                        }
                    }

                    Intent intent = new Intent(activity, DeleteImageActivity.class);
                    intent.putExtra("urlList", (Serializable) urlList);
                    intent.putExtra("fileList", (Serializable) fileList);// tangkun
                    // 传递文件的集合过去
                    intent.putExtra("index", position);
                    activity.startActivityForResult(intent, REQUEST_CODE_CAPTURE_IMAGE);
                }
            });
        }
        return convertView;
    }

    /**
     * 根据指定的图像路径和大小来获取缩略图 此方法有两点好处： 1.
     * 使用较小的内存空间，第一次获取的bitmap实际上为null，只是为了读取宽度和高度，
     * 第二次读取的bitmap是根据比例压缩过的图像，第三次读取的bitmap是所要的缩略图。 2.
     * 缩略图对于原图像来讲没有拉伸，这里使用了2.2版本的新工具ThumbnailUtils，使 用这个工具生成的图像不会被拉伸。
     *
     * @param imagePath 图像的路径
     * @param width     指定输出图像的宽度
     * @param height    指定输出图像的高度
     * @return 生成的缩略图
     */
    private Bitmap getImageThumbnail(String imagePath, int width, int height) {
        Bitmap bitmap = null;
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        // 获取这个图片的宽和高，注意此处的bitmap为null
        bitmap = BitmapFactory.decodeFile(imagePath, options);
        options.inJustDecodeBounds = false; // 设为 false
        // 计算缩放比
        int h = options.outHeight;
        int w = options.outWidth;
        int beWidth = w / width;
        int beHeight = h / height;
        int be = 1;
        if (beWidth < beHeight) {
            be = beWidth;
        } else {
            be = beHeight;
        }
        if (be <= 0) {
            be = 1;
        }
        options.inSampleSize = be;
        // 重新读入图片，读取缩放后的bitmap，注意这次要把options.inJustDecodeBounds 设为 false
        bitmap = BitmapFactory.decodeFile(imagePath, options);
        // 利用ThumbnailUtils来创建缩略图，这里要指定要缩放哪个Bitmap对象
        bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height, ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
        return bitmap;
    }

}
